package guijavacommander;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;

/**
 * User: Deady
* Date: 15.07.2009
* Time: 13:32:03
*/
class FileTreeNode extends DefaultMutableTreeNode {

    private boolean loaded = false;
    private FileTreeNode[] children;

    FileTreeNode(File file) {
        super(file);
        if (file.getParentFile()!=null) {
            setParent(new FileTreeNode(file.getParentFile()));
        }
    }


    public boolean isLoaded() {
        return loaded;
    }

    public void setLoaded(boolean loaded) {
        this.loaded = loaded;
        if (loaded) {
            File file = (File) getUserObject();
            final File[] files = file.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    return !pathname.isHidden();
                }
            });
            int index = 0;
            children = new FileTreeNode[files != null ? files.length : 0];
            if (files != null) {
                Arrays.sort(files, new FileSystemComparator());
                for (File f : files) {
                    children[index] = new FileTreeNode(f);
                    children[index].setParent(this);
                    index++;
                }
            }
        }
        else {
            children = null;
        }
    }

    public FileTreeNode[] getChildren() {
        if (children == null) {
            setLoaded(true);
        }
        return children;
    }

    @Override
    public TreeNode getChildAt(int index) {
        return getChildren()[index];
    }

    @Override
    public int getChildCount() {
        return getChildren().length;
    }


    @Override
    public int getIndex(TreeNode aChild) {
        int i = 0;
        for (FileTreeNode c : children) {
            if (c.equals(aChild)) {
                return i;
            }
            i++;
        }
        return super.getIndex(aChild);
    }

    @Override
    public boolean isLeaf() {
        File f = (File) getUserObject();
        return !f.isDirectory();
    }

    @Override
    public String toString() {
        File f = (File) getUserObject();
        return f.getName();
    }



    private static class FileSystemComparator implements Comparator<File> {
        public int compare(File o1, File o2) {
            if (o1.isDirectory() && o2.isDirectory()) {
                return o1.getName().compareToIgnoreCase(o2.getName());
            }
            else if (o1.isDirectory() && !o2.isDirectory()) {
                return -1;
            }
            else if (!o1.isDirectory() && o2.isDirectory()) {
                return 1;
            }
            else {
                return o1.getName().compareToIgnoreCase(o2.getName());
            }
        }
    }
}
